import { createRouter, createWebHistory } from 'vue-router'

const pages =
    import.meta.glob('../views/**/pageConfig.js', {
        eager: true,
        import: 'default',
    })

const components =
    import.meta.glob('../views/**/index.vue')

const routes = Object.entries(pages).map(([path, meta]) => {
    const compPath = path.replace('pageConfig.js', 'index.vue')
    const routePath = path.replace('../views/', '').replace('/pageConfig.js', '') || '/'
    const name = routePath.split('/').filter(Boolean).join('-') || 'index'

    // 如果有子页面，处理子页面
    const children = meta.children || []

    const childRoutes = children.map(child => {
        const childPath = `${routePath}/${child.path}`
        const childCompPath = `${path.replace('../views/', '../views/')}`.replace('pageConfig.js', `${child.path}/index.vue`)
        return {
            path: child.path,
            name: child.name,
            component: components[childCompPath],
            meta: {...child },
        }
    })

    return {
        path: routePath === '/' ? 'Index' : `/${routePath}`,
        // path: `/${routePath}`,
        name,
        component: components[compPath],
        meta,
        children: childRoutes,
    }
})

const router = createRouter({
    history: createWebHistory(),
    routes,
})

// 添加默认路由，如登录页面
const defaultRoutes = [{
        path: '/login',
        name: 'login',
        component: () =>
            import ('../views/login/index.vue'), // 假设登录页面路径
        meta: { requiresAuth: false }
    },
    {
        path: '/',
        redirect: '/Index' // 或其他默认页面
    }
]

// 全局前置守卫
router.beforeEach((to, from, next) => {
    // 定义白名单，不需要登录验证的路径
    const whiteList = ['/login', '/register', '/Index']

    // 获取token或其他认证信息
    const hasToken = localStorage.getItem('token') || sessionStorage.getItem('token')

    // 如果目标路由需要认证
    if (to.meta.requiresAuth !== false) {
        // 如果没有token且不在白名单中
        if (!hasToken && !whiteList.includes(to.path)) {
            // 重定向到登录页面
            next('/login')
        } else {
            next()
        }
    } else {
        next()
    }
})
export default router